import CircleProgresView from '@/components/MyCircleProgressView';
import Strings from '@/i18n';
import { isHeating } from '@/utils';
import { useActions, useProps } from '@ray-js/panel-sdk';
import { Button, Text, View } from '@ray-js/ray';
import { Image } from '@ray-js/smart-ui';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import homeIcon from '../../res/imgs/ic_main_home.png';
import Styles from './index.module.less'; // 引入模块化样式
// 使用 React.memo 包裹组件以减少不必要的重新渲染
const MainPageViewComponent: React.FC = () => {
  const colorSelected = '#DD3F12';
  const colorNormal = '#B4B4B4';

  const actions = useActions();

  const heatMode = useProps(props => props.mode);//加热模式,dp4: 枚举值: auto, manual_high, manual_low 
  console.log('首页heatMode', heatMode);
  const myHeatSet = useProps(props => props.Heat_Program);
  console.log('myHeatSet', myHeatSet);

  let isHeated = isHeating(myHeatSet, heatMode);
  console.log('是否正在加热', isHeated);
  const flameMode = useProps(props => props.Flame_Mode);//火焰模式,dp108: 枚举值: auto, manual	

  console.log('首页flameMode', flameMode);

  const temp_unit_convert = useProps(props => props.temp_unit_convert);//当前温标
  console.log('当前温标', 'temp_unit_convert:' + temp_unit_convert);

  const tempCurrentC = useProps(props => props.temp_current);//当前摄氏度温度，数值范围: 0-50, 间距: 1, 倍数: 0, 单位: °C

  const tempCurrentF = useProps(props => props.temp_current_f);//当前华氏度温度，数值范围: 32-122, 间距: 1, 倍数: 0, 单位: ℉

  const tempSetC = useProps(props => props.temp_set);//当前摄氏度的目标温度，数值范围: 5-40, 间距: 1, 倍数: 0, 单位: °C	

  const tempSetF = useProps(props => props.temp_set_f);//当前华氏度的目标温度，数值范围: 41-104, 间距: 1, 倍数: 0, 单位: ℉	

  let tempCurrent = 0;//当前温度


  function getCurrentUnit() { //获取当前单位和目前温度
    if (temp_unit_convert === 'c') {//摄氏度
      tempCurrent = tempCurrentC;
      return '°C';
    } else {
      tempCurrent = tempCurrentF;
      return '°F';
    }
  }
  let currentUnit = getCurrentUnit();
  console.log('当前温度', tempCurrent);
  const canThump = heatMode !== 'auto' //是否可控温
  console.log('当前canThump', canThump);
  const value = getValue();////记录当前圆环进度的百分比
  console.log('打印进度', value);

  function getValue(): number {
    let endValue = 0;
    if (temp_unit_convert === 'c') {//摄氏度
      endValue = (tempSetC - 5) / (40 - 5) * 100;
      console.log('摄氏度的当前目标刻度:' + endValue + ',tempSetC:' + tempSetC);
    } else { //话是对
      endValue = (tempSetF - 41) / (104 - 41) * 100;
      console.log('华氏度的当前目标刻度:' + endValue + ',tempSetF:' + tempSetF);
    }
    return endValue;
  }

  const [tempSet, setTemp] = useState(() => {
    return temp_unit_convert === 'c' ? tempSetC : tempSetF;//目标温度，temp_set
  })

  console.log('目标温度-打印', tempSet + ',tempSetC:' + tempSetC + ",tempSetF:" + tempSetF);

  const onClickFlameManual = useCallback(() => { //点击火焰手动

    console.log('点击了火焰手动');
    if (flameMode !== 'manual') {
      actions.Flame_Mode.set('manual');
    }
  }, [flameMode]);

  const onClickFlameAuto = useCallback(
    () => { //点击火焰自动
      console.log('点击了火焰自动');
      if (flameMode !== 'auto') {
        actions.Flame_Mode.set('auto');
      }

    }, [flameMode]);

  const onClickHeatLow = useCallback(
    () => { //点击加热低档
      console.log('点击了加热低档');
      if (heatMode !== 'manual_low') {
        actions.mode.set('manual_low');
      }
    }, [heatMode]);
  const onClickHeatHigh = useCallback(
    () => { //点击加热高档
      console.log('点击了加热高档');
      if (heatMode !== 'manual_high') {
        actions.mode.set('manual_high');
      }
    }, [heatMode]);

  const onClickHeatAuto = useCallback( //点击加热自动档
    () => { //点击加热自动
      console.log('点击了加热自动');
      if (heatMode !== 'auto') {
        actions.mode.set('auto');
        console.log('发送加热自动指令');
      }
    }, [heatMode]);

  const handleMove = (v: number) => {
    console.warn('handleMove', v);//这里要将0-100换算成，显示的温度值
    const currentTempUnit = tempUnitConvertRef.current;
    setTemp(getSetValue(currentTempUnit, v))
    console.warn('handleEnd', v + ',temp_unit_convert:' + currentTempUnit + ",temp_set:" + tempSet);

  };

  const tempUnitConvertRef = useRef(temp_unit_convert);

  useEffect(() => {
    tempUnitConvertRef.current = temp_unit_convert;
    console.log('重新赋值温标', temp_unit_convert);

    setTemp(temp_unit_convert === 'c' ? tempSetC : tempSetF)
  }, [temp_unit_convert, tempSetF]);//这里将tempSetC去掉，因为这两个会一起变。只要等f更新后再执行就可以了

  const handleEnd = useCallback((v: number) => {
    const currentTempUnit = tempUnitConvertRef.current;
    console.warn('handleEnd', v + ',temp_unit_convert:' + currentTempUnit);

    let setValue = getSetValue(currentTempUnit, v);
    if (currentTempUnit === 'c') {
      actions.temp_set.set(setValue);
    } else {
      actions.temp_set_f.set(setValue);
    }

  }, []); // 添加依赖项，当temp_unit_convert 温标改变时，重新创建函数

  /**
   * 
   * @param unit 根据当前的进度换算对应的温度目标值
   * @param v 
   * @returns 
   */
  function getSetValue(unit: string, v: number): number {
    let setValue = 0;
    if (unit === 'c') {
      setValue = Math.round(5 + v * 35 / 100);
      if (setValue < 5) setValue = 5;
      if (setValue > 40) setValue = 40;
    } else {
      setValue = Math.round(41 + v * 63 / 100);
      if (setValue < 41) setValue = 41;
      if (setValue > 104) setValue = 104;
    }
    return setValue;
  }

  return (

    <View className={Styles.container}>
      <View className={Styles.circleandtext}>

        <CircleProgresView
          value={value}
          innerRingRadius={125}
          radius={145}
          colorType={0}
          hideThumb={!canThump}
          onTouchMove={handleMove}
          onTouchEnd={handleEnd}
          renderInnerCircle={() => (
            <View
              style={{
                flexDirection: 'column',
                width: '250rpx',
                height: '250rpx',
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
              }}
            >
              <View style={{ display: 'flex', flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}>
                <Text style={{ fontSize: '15px', opacity: 0 }}>{tempCurrent}</Text>
                <Text style={{ fontSize: '12px', opacity: 0 }}>{currentUnit}</Text>
                <Image useLoadingSlot width="51rpx" height="40rpx" src={homeIcon} fit="contain" slot={{
                  loading: <View style={{ width: "51rpx", height: '40rpx', backgroundColor: '#606060' }}></View>
                }} />
                <View style={{ display: 'flex', flexDirection: 'row', alignItems: 'flex-start' }}>
                  <Text style={{ fontSize: '15px', color: colorSelected }}>{tempCurrent}</Text>
                  <Text style={{ fontSize: '12px', color: colorSelected }}>{currentUnit}</Text>
                </View>
              </View>

              <View style={{ display: 'flex', flexDirection: 'row', alignItems: 'flex-start' }}>
                <Text style={{ fontSize: '12px', color: '#ffffff', paddingTop: '20rpx', opacity: 0 }}>{currentUnit}</Text>
                <Text style={{ fontSize: '70px', color: '#ffffff' }}>{tempSet}</Text>
                <Text style={{ fontSize: '12px', color: '#ffffff', paddingTop: '20rpx' }}>{currentUnit}</Text>
              </View>
              {/* // opacity: isVisible ? 1 : 0 // isVisible 是一个布尔值，控制显示或隐藏 */}
              <Text style={{ color: '#DF3C13', fontSize: '15px', fontWeight: "bold", opacity: isHeated ? 1 : 0 }}>{Strings.getLang('m_heating')}</Text>
              <View>
              </View>
            </View>
          )}
        />
        <View>
          <View className={Styles.textBar}>
            <Button hoverClassName='none' className={Styles.buttontext} style={{ minWidth: '0px', backgroundColor: '#737373', marginRight: '4px', flex: 2 }} >{Strings.getLang('m_flame')}</Button>
            <Button onClick={onClickFlameManual} className={Styles.buttontext} style={{ fontSize: '16px', backgroundColor: flameMode === 'manual' ? colorSelected : colorNormal, marginRight: '4px', flex: 4 }} hoverStartTime={0} hoverStayTime={0}>{Strings.getLang('m_manual')}</Button>
            <Button onClick={onClickFlameAuto} className={Styles.buttontext} style={{ borderRadius: '3px', fontSize: '16px', backgroundColor: flameMode === 'auto' ? colorSelected : colorNormal, flex: 2 }} hoverStartTime={0} hoverStayTime={0}>{Strings.getLang('m_auto')}</Button>
          </View>
          <View className={Styles.textBar}>
            <Button className={Styles.buttontext} hoverClassName="none" style={{ backgroundColor: '#737373', marginRight: '4px', flex: 2 }} >{Strings.getLang('m_heater')}</Button>
            <Button onClick={onClickHeatLow} className={Styles.buttontext} style={{ backgroundColor: heatMode === 'manual_low' ? colorSelected : colorNormal, marginRight: '4px', flex: 2 }} hoverStartTime={0} hoverStayTime={0}>{Strings.getLang('m_low')}</Button>
            <Button onClick={onClickHeatHigh} className={Styles.buttontext} style={{ backgroundColor: heatMode === 'manual_high' ? colorSelected : colorNormal, marginRight: '4px', flex: 2 }} hoverStartTime={0} hoverStayTime={0}>{Strings.getLang('m_high')}</Button>
            <Button onClick={onClickHeatAuto} className={Styles.buttontext} style={{ backgroundColor: heatMode === 'auto' ? colorSelected : colorNormal, flex: 2 }} hoverStartTime={0} hoverStayTime={0}>{Strings.getLang('m_auto')}</Button>
          </View>
        </View>
      </View>
    </View>
  );
};

export default React.memo(MainPageViewComponent); // 使用 React.memo 减少不必要的重新渲染